//
//  RWRegisterViewController.m
//  RedWine
//
//  Created by Liufangfang on 2016/12/31.
//  Copyright © 2016年 HuiBangKe. All rights reserved.
//

#import "RWRegisterViewController.h"
#import "FTYInfoVertifyTools.h"
#import "RWSetPasswordViewController.h"
#import "DisclaimerViewController.h"

#define kRegisterTextFieldTagBase 450

@interface RWRegisterViewController ()<UITextFieldDelegate>{

    NSArray *imageIcons;
    NSArray *textFields;
}

@property (nonatomic, strong) UIButton *selectBtn;
@property (nonatomic, strong) UIButton *nextBtn;

@property (nonatomic, strong) UITextField *phoneNumberTF;
@property (nonatomic, strong) UITextField *codeTF;
@property (nonatomic, strong) UITextField *rePhoneNumberTF;

@end

@implementation RWRegisterViewController

#pragma mark - View LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initObjects];
    [self setNavigation];
    [self setRegisterUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Load Datas

- (void)initObjects{

    imageIcons = @[@"myiphone_icon", @"code_icon", @"code_icon"];
    textFields = @[@"请输入手机号", @"请输入验证码", @"请输入推荐人手机号码"];
}

#pragma mark - Config UI

- (void)setNavigation{
    
    self.title = @"注册";
}

- (void)setRegisterUI{
    
    _registerTV = [[FTYTouchTableView alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, FTY_SCREEN_HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:_registerTV];
    _registerTV.backgroundColor = [FTYColor getEEEEEEColorWithAlpha:1.];
    _registerTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    _registerTV.scrollEnabled = NO;
    _registerTV.dataSource = self;
    _registerTV.delegate = self;
    _registerTV.touchDelegate = self;
    _registerTV.tableFooterView = [self setFooterUI];
}

- (UIView *)setFooterUI{
    
    UIView *footerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, 200.*FTY_HEIGHT_BASE)];
    
    UIButton *selectBtn = [[UIButton alloc] init];
    [footerV addSubview:selectBtn];
    [selectBtn setImage:[UIImage imageNamed:@"selected_icon"] forState:UIControlStateNormal];
    [selectBtn setImage:[UIImage imageNamed:@"noselected_icon"] forState:UIControlStateSelected];
    [selectBtn addTarget:self action:@selector(selectBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(6.*FTY_HEIGHT_BASE);
        make.width.height.mas_equalTo(30.*FTY_WIDTH_BASE);
    }];
    _selectBtn = selectBtn;
    
    //NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@"我同意注册协议"];
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@"我已满18岁并接受汇邦客注册条款"];
    
    [attrStr addAttributes:@{NSForegroundColorAttributeName: [FTYColor getMainColorWithAlpha:1.]} range:NSMakeRange(12, attrStr.length - 12)];
    UILabel *textLab = [[UILabel alloc] init];
    [footerV addSubview:textLab];
    textLab.attributedText = attrStr;
    textLab.font = FTY_FONTTSIZE(15);
    [textLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(13.*FTY_HEIGHT_BASE);
        make.left.mas_equalTo(selectBtn.mas_right).offset(6.*FTY_WIDTH_BASE);
    }];
    
    UIButton *declaimBtn = [[UIButton alloc] init];
    [footerV addSubview:declaimBtn];
    [declaimBtn addTarget:self action:@selector(declaimBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [declaimBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(textLab);
        make.width.height.mas_equalTo(textLab);
    }];
    
    FTYButton *nextBtn = [FTYButton createButtonWithTitle:@"下一步" tColor:[UIColor blackColor] fontSize:15.*FTY_WIDTH_BASE backGroundColor:[FTYColor getMainColorWithAlpha:1.] cornerRadius:15.*FTY_WIDTH_BASE];
    [footerV addSubview:nextBtn];
    [nextBtn addTarget:self action:@selector(nextBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(textLab.mas_bottom).offset(20.*FTY_HEIGHT_BASE);
        make.left.mas_equalTo(10.*FTY_WIDTH_BASE);
        make.width.mas_equalTo(FTY_SCREEN_WIDTH - 15.*FTY_WIDTH_BASE *2);
        make.height.mas_equalTo(40.*FTY_HEIGHT_BASE);
    }];
    _nextBtn = nextBtn;
    
    return footerV;
}

#pragma mark - Config Invoke Methods

- (void)selectBtnAction:(UIButton *)btn{

    btn.selected = ! btn.selected;
    if (btn.selected) {
        _nextBtn.backgroundColor = [UIColor lightGrayColor];
        _nextBtn.userInteractionEnabled = NO;
    } else {
        _nextBtn.backgroundColor = [FTYColor getMainColorWithAlpha:1.];
        _nextBtn.userInteractionEnabled = YES;
    }
}

#pragma mark - Notificaiton Method

#pragma mark - Notificaiton Invoke Methods

#pragma mark - <UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 60.*FTY_HEIGHT_BASE;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    UILabel *noteLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, 60.*FTY_HEIGHT_BASE)];
    noteLab.text = @"本商城位会员制，无推荐人不能注册";
    noteLab.textColor = [FTYColor grayColor];
    noteLab.textAlignment = NSTextAlignmentCenter;
    noteLab.font = FTY_FONTTSIZE(15);
    [noteLab sizeToFit];
    return noteLab;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 60.*FTY_HEIGHT_BASE;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString * const registerID = @"registerID";
    UITableViewCell *registerCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:registerID];
    registerCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSInteger row = indexPath.row;
    registerCell.imageView.image = [UIImage imageNamed:imageIcons[row]];
    
    UITextField *textField = [[UITextField alloc] init];
    [registerCell addSubview:textField];
    textField.placeholder = textFields[row];
    textField.font = FTY_FONTTSIZE(14);
    textField.delegate = self;
    textField.tag = kRegisterTextFieldTagBase + row;
    textField.keyboardType = UIKeyboardTypeNumberPad;
    [textField sizeToFit];
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(registerCell);
        make.left.mas_equalTo(registerCell.imageView.mas_right).offset(10.*FTY_WIDTH_BASE);
        make.right.mas_offset(-10.*FTY_WIDTH_BASE);
    }];
    
    if (1 == row) {
        
        UIButton *getCodeBtn = [FTYButton createButtonWithTitle:@"获取验证码" tColor:[UIColor blackColor] fontSize:13.*FTY_WIDTH_BASE backGroundColor:[FTYColor getMainColorWithAlpha:1.] cornerRadius:15.*FTY_WIDTH_BASE];
        [registerCell addSubview:getCodeBtn];
        [getCodeBtn addTarget:self action:@selector(getCodeBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [getCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(registerCell.mas_centerY);
            make.right.mas_equalTo(-10.*FTY_WIDTH_BASE);
            make.width.mas_equalTo(80.*FTY_WIDTH_BASE);
            make.height.mas_equalTo(30.*FTY_HEIGHT_BASE);
        }];
    }
    
    if (0 == row) {
        _phoneNumberTF = textField;
    } else if(1 == row) {
        _codeTF = textField;
    } else {
        _rePhoneNumberTF = textField;
    }

    //底部线
    UIView *line = [[UIView alloc] init];
    [registerCell addSubview:line];
    line.backgroundColor = [UIColor grayColor];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.height.mas_equalTo(.5*FTY_HEIGHT_BASE);
    }];
    
    return registerCell;
}

#pragma mark - <UITableViewDelegate>

#pragma mark - <UITextFieldDelegate>

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    [textField resignFirstResponder];
    return YES;
}

#pragma mark - <FTYTouchTableViewDelegate>

- (void)tableView:(UITableView *)tableView touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    [_phoneNumberTF resignFirstResponder];
    [_codeTF resignFirstResponder];
    [_rePhoneNumberTF resignFirstResponder];
}

#pragma mark - Private Invoke Methods

- (void)getCodeBtnAction:(UIButton *)btn{
    
    NSString *phoneNumber = _phoneNumberTF.text;
    
    [FTYInfoVertifyTools phoneNumberVertify:phoneNumber showAtView:self.view];

    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=verify&type=reg&member_mobile=%@", phoneNumber] parameters:nil block:^(id result, NSError *error) {
        
        if (!error) {
            
            NSInteger code = [[[result objectForKey:@"err"] objectForKey:@"errorcode"] integerValue];
            NSString *info = [[result objectForKey:@"err"] objectForKey:@"errorinfo"];
            if (0 == code) {
                [[FTYToastView alloc] addTitle:@"验证码已发送～" addView:self.view];
            } else {
                [[FTYToastView alloc] addTitle:info addView:self.view];
            }
        } else {
            NSLog(@"=====%@", error);
        }
    }];
}
- (void)declaimBtnAction:(UIButton *)btn{
    DisclaimerViewController *disclaimController = [[DisclaimerViewController alloc] init];
    [self.navigationController pushViewController:disclaimController animated:YES];
}
- (void)nextBtnAction:(UIButton *)btn{

    NSString *code = _codeTF.text;
    NSString *phoneNumber = _phoneNumberTF.text;
    NSString *rePhoneNumber = _rePhoneNumberTF.text;
    
    [FTYInfoVertifyTools phoneNumberVertify:phoneNumber showAtView:self.view];
    [FTYInfoVertifyTools phoneNumberVertify:rePhoneNumber showAtView:self.view];
    
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=checkRegInfo&type=reg&member_mobile=%@&verify=%@&inv_mobile=%@", phoneNumber, code, rePhoneNumber] parameters:nil block:^(id result, NSError *error) {
        
        if (!error) {
            
            NSInteger codeInfo = [[[result objectForKey:@"err"] objectForKey:@"errorcode"] integerValue];
            NSString *info = [[result objectForKey:@"err"] objectForKey:@"errorinfo"];
            if (0 == codeInfo) {
                //TODO:成功之后是否还需要页面弹框提示？其他页面同问！
//                NSLog(@"注册成功～");
                RWSetPasswordViewController *setPasswordVC = [[RWSetPasswordViewController alloc] init];
                setPasswordVC.phoneNumber = phoneNumber;
                setPasswordVC.code = code;
                setPasswordVC.rePhoneNumber = rePhoneNumber;
                [self.navigationController pushViewController:setPasswordVC animated:YES];
            } else {
                [[FTYToastView alloc] addTitle:info addView:self.view];
            }
        } else {
            NSLog(@"======%@", error);
        }
    }];
}

@end
